package handlers

import (
	"encoding/json"
	"food-go/cache"
	"food-go/models"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var food []models.Food
	reids_key := "list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, reids_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Debug().Find(&food)
		jsonData, _ := json.Marshal(food)
		cache.Rdb.Set(cache.Ctx, reids_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &food)
	}
	var total int64
	models.DB.Model(&models.Food{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  food,
		"total": total,
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var food models.Food
	reids_key := "detail_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, reids_key).Result()
	if cacheData == "" {
		models.DB.Where("id = ?", id).Debug().Find(&food)
		jsonData, _ := json.Marshal(food)
		cache.Rdb.Set(cache.Ctx, reids_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &food)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": food,
	})
	return
}
func Add(c *gin.Context) {
	title := c.PostForm("title")
	desc := c.PostForm("desc")
	price, _ := strconv.Atoi(c.PostForm("price"))
	score, _ := strconv.Atoi(c.PostForm("score"))
	data := models.Food{
		Title: title,
		Desc:  desc,
		Price: price,
		Score: score,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "ok",
			"data": data,
		})
		return
	}
}
